package com.fucius.study.leetcode;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Aes {

    public static SecretKey initKey(String keyStr) throws Exception{
        MessageDigest sha256Digest;
        sha256Digest = MessageDigest.getInstance("SHA-256");
        byte[] bytes = Arrays.copyOf(sha256Digest.digest(keyStr.getBytes(StandardCharsets.UTF_8)), 16);
        System.out.println(byte2Hex(bytes));
        return new SecretKeySpec(bytes, "AES");
    }

    public static IvParameterSpec initIV(String ivSource)  throws Exception {
        MessageDigest sha256Digest;
        sha256Digest = MessageDigest.getInstance("SHA-256");
        byte[] bytes = Arrays.copyOf(sha256Digest.digest(ivSource.getBytes(StandardCharsets.UTF_8)), 16);
        System.out.println(byte2Hex(sha256Digest.digest(ivSource.getBytes(StandardCharsets.UTF_8))));
        System.out.println(byte2Hex(bytes));
        return new IvParameterSpec(bytes);
    }

    private static String byte2Hex(byte[] bytes){
        System.out.println(Arrays.toString(bytes));
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        Pattern pattern = Pattern.compile("");
        Matcher matcher = pattern.matcher("");
        matcher.find();
        return stringBuffer.toString();
    }

    public static byte[] decrypt(byte[] encrypted,String keyStr,String ivStr)  throws Exception{
        Cipher cipher= Cipher.getInstance("AES/CTR/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, initKey(keyStr), initIV(ivStr));
        return cipher.doFinal(encrypted);
    }

    public static byte[] encrypt(byte[] encrypted,String keyStr,String ivStr)  throws Exception{
        Cipher cipher= Cipher.getInstance("AES/CTR/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, initKey(keyStr), initIV(ivStr));
        return cipher.doFinal(encrypted);
    }

    public static void main(String[] args) {
        try {
            String appKey = "zc_test";
            byte[] encryptByte = Base64.getDecoder().decode("5TMVT8H4yTSSoING+afhRlGcCZAIxTs8Z7o3vGpid6tF2aF7C73uZ44qMopuNPCFmwOLOJ8xViCTHUfe/xYZSb71/VRSEDeIqqwN4eg=");
            String decryptStr = new String(decrypt(encryptByte,appKey,appKey),"UTF-8");
            System.out.println("解密结果："+decryptStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
